// 全局变量
let apiData = [];
let isMonitoring = true;
let maxRecords = 100; // 最大记录数量限制
let timeoutThreshold = 3000; // 默认超时阈值

// DOM元素
const apiList = document.getElementById('apiList');
const noData = document.getElementById('noData');
const pauseBtn = document.getElementById('pauseBtn');
const clearBtn = document.getElementById('clearBtn');
const timeoutInput = document.getElementById('timeoutThreshold');
const saveThresholdBtn = document.getElementById('saveThresholdBtn');

// 初始化
document.addEventListener('DOMContentLoaded', () => {
  // 从存储中加载数据
  chrome.storage.local.get(['apiData', 'isMonitoring', 'timeoutThreshold'], (result) => {
    if (result.apiData) {
      apiData = result.apiData;
      renderApiList();
    }
    
    if (result.isMonitoring !== undefined) {
      isMonitoring = result.isMonitoring;
      updatePauseButton();
    }

    if (result.timeoutThreshold !== undefined) {
      timeoutThreshold = result.timeoutThreshold;
      timeoutInput.value = timeoutThreshold;
    }
  });
  
  // 设置按钮事件监听器
  pauseBtn.addEventListener('click', toggleMonitoring);
  clearBtn.addEventListener('click', clearData);
  saveThresholdBtn.addEventListener('click', saveThreshold);
  
  // 监听来自background.js的消息
  chrome.runtime.onMessage.addListener((message) => {
    if (message.type === 'API_RESPONSE' && isMonitoring) {
      addApiData(message.data);
    }
  });
});

// 切换监控状态
function toggleMonitoring() {
  isMonitoring = !isMonitoring;
  updatePauseButton();
  
  // 保存监控状态
  chrome.storage.local.set({ isMonitoring });
  
  // 通知background.js监控状态变化
  chrome.runtime.sendMessage({ 
    type: 'TOGGLE_MONITORING', 
    isMonitoring 
  });
}

// 更新暂停按钮文本
function updatePauseButton() {
  pauseBtn.textContent = isMonitoring ? '暂停' : '继续';
}

// 清空数据
function clearData() {
  apiData = [];
  renderApiList();
  
  // 保存空数据
  chrome.storage.local.set({ apiData });
  
  // 通知background.js清空数据
  chrome.runtime.sendMessage({ type: 'CLEAR_DATA' });
}

// 添加API数据
function addApiData(data) {
  // 添加到数组开头（最新的在前面）
  apiData.unshift(data);
  
  // 限制最大记录数
  if (apiData.length > maxRecords) {
    apiData = apiData.slice(0, maxRecords);
  }
  
  // 保存数据
  chrome.storage.local.set({ apiData });
  
  // 更新UI
  renderApiList();
}

// 保存超时阈值
function saveThreshold() {
  const newThreshold = parseInt(timeoutInput.value);
  if (newThreshold >= 100) {
    timeoutThreshold = newThreshold;
    chrome.storage.local.set({ timeoutThreshold });
    renderApiList(); // 重新渲染列表以更新状态显示
  }
}

// 渲染API列表
function renderApiList() {
  // 如果没有数据，显示提示信息
  if (apiData.length === 0) {
    apiList.innerHTML = '';
    noData.style.display = 'block';
    return;
  }
  
  // 隐藏提示信息
  noData.style.display = 'none';
  
  // 按响应时间倒序排序
  const sortedData = [...apiData].sort((a, b) => b.duration - a.duration);
  
  // 生成HTML
  let html = '';
  
  sortedData.forEach(item => {
    const isTimeout = item.duration > timeoutThreshold;
    const statusClass = isTimeout ? 'status-timeout' : 'status-normal';
    const statusText = isTimeout ? '超时' : '正常';
    const statusCode = item.status === 'error' ? '请求失败' : `状态码: ${item.status}`;
    const timestamp = new Date(item.timestamp).toLocaleString();
    
    html += `
      <li class="api-item">
        <div class="api-url" title="${item.url}">${item.url}</div>
        <div class="api-details">
          <span class="api-time">${item.duration} ms</span>
          <span class="api-status ${statusClass}">${statusText}</span>
        </div>
        <div class="api-extra" style="display: none;">
          <div class="api-status-code">${statusCode}</div>
          <div class="api-timestamp">${timestamp}</div>
        </div>
      </li>
    `;
  });
  
  apiList.innerHTML = html;
  
  // 添加双击事件监听器
  document.querySelectorAll('.api-item').forEach(item => {
    item.addEventListener('dblclick', () => {
      // 切换详细信息的显示状态
      const extraInfo = item.querySelector('.api-extra');
      extraInfo.style.display = extraInfo.style.display === 'none' ? 'block' : 'none';
      
      // 同时切换URL的展开状态
      const urlElement = item.querySelector('.api-url');
      urlElement.classList.toggle('expanded');
    });
  });
}